<h1 class="page-header">
    <small>编辑商品</small>
</h1>
<div class="panel panel-inverse" data-sortable-id="form-stuff-1">
    <div class="panel-heading">
        <h4 class="panel-title">商品信息</h4>
    </div>
    <div class="panel-body" style="background-color:#f0f3f4;padding-left: 0px;padding-right: 0px;">
        <ul class="nav nav-tabs">
            <li id="base-info" class="nav-item">
                <a href="javascript:;" data-bs-toggle="tab" class="nav-link active">基础信息</a>
            </li>
            <li id="extend-info" class="nav-item">
                <a href="javascript:;" data-bs-toggle="tab" class="nav-link">扩展信息</a>
            </li>
            <li id="detail-info" class="nav-item">
                <a href="javascript:;" data-bs-toggle="tab" class="nav-link">商品详情</a>
            </li>
        </ul>
        <div class="tab-content bg-white p-30 rounded-bottom">
            <div class="tab-pane active show" id="base-info-tab">
                <form class="form-horizontal" id="baseForm" name="baseForm" action="" method="post">
                    <input type="hidden" class="form-control" id="goodsId" name="goodsId" value="${goods.id}"/>
                    <#if storeId < 1>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>所属店铺：</label>
                        <div class="col-md-3">
                            <select class="form-control" name="storeId" id="storeId">
                                <option value="0" <#if goods.storeId == 0>selected</#if> >全部</option>
                                <#if storeList?has_content && storeList?exists>
                                <#list storeList as pf>
                                <option value="${pf.id}" <#if pf.id == goods.storeId>selected</#if> >${pf.name}</option>
                                </#list>
                                </#if>
                            </select>
                        </div>
                    </div>
                    </#if>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>商品名称：</label>
                        <div class="col-md-3">
                            <input type="text" id="name" class="form-control" name="name" value="${goods.name}" placeholder="商品名称，长度1-100" rangelength="1, 100" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>商品分类：</label>
                        <div class="col-md-3">
                            <select class="form-control" name="cateId" id="cateId">
                               <#list cateList as cate><option value="${cate.id}" <#if (cate.id == goods.cateId)>selected</#if>>${cate.name}</option></#list>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>商品条码：</label>
                        <div class="col-md-3">
                            <input type="text" id="goodsNo" class="form-control" value="${goods.goodsNo}" name="goodsNo" placeholder="商品条码，长度1-50" rangelength="1, 50" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>商品图片：</label>
                        <div class="col-md-4">
                            <div class="upload-list">
                                <#if images ? size gt 0>
                                <#list images as img>
                                <div class="upload-item">
                                    <img name="image${img_index+1}" class="image" id="image${img_index+1}" src="${imagePath}${img}">
                                    <input type="file" name="picture${img_index+1}" id="picture${img_index+1}" style="display: inline-block" onchange="ajaxFileUpload('${img_index+1}', '${rc.contextPath}/backend');">
                                    <a class="label label-danger small-btn delete" href="javascript:void(0)" title="删除该图片"><i class="fa fa-remove"></i>删除</a>
                                    <div class="tip">（格式：jpeg/jpg/png）</div>
                                    <input type="hidden" placeholder="存储路径" name="image" id="filePath${img_index+1}" value="${img}" onchange="changeImagePath('<@mh.static/>', '${img_index+1}')">
                                </div>
                                </#list>
                                <#else>
                                <div class="upload-item">
                                    <img name="image1" class="image" id="image1" src="<@mh.static/>/defaultImage/none.png">
                                    <input type="file" name="picture1" id="picture1" style="display: inline-block" onchange="ajaxFileUpload(1, '${rc.contextPath}/backend');">
                                    <a class="label label-danger small-btn delete" href="javascript:void(0)" title="删除该图片"><i class="fa fa-remove"></i>删除</a>
                                    <div class="tip">（格式：jpeg/jpg/png）</div>
                                    <input type="hidden" placeholder="存储路径" name="image" id="filePath1" value="" onchange="changeImagePath('<@mh.static/>', '1')">
                                </div>
                                </#if>
                            </div>
                            <div class="add-goods-image btn btn-small btn-success"><i class="fa fa-plus"></i> 新增图片</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">排序：</label>
                        <div class="col-md-2">
                            <input type="text" id="sort" class="form-control" value="<#if goods.sort>${goods.sort}<#else>0</#if>" name="sort" placeholder="排序，正整数" rangelength="1, 10"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">状态：</label>
                        <div class="col-md-2">
                            <select class="form-control" name="status" id="status">
                                <option <#if goods.status == 'A'>selected</#if> value="A">上架</option>
                                <option <#if goods.status == 'D'>selected</#if> value="D">下架</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"></label>
                        <div class="col-md-9">
                            <button type="button" id="submitBase" class="btn btn-sm btn-success">提交</button>
                            <button type="button" class="btn btn-sm btn-danger" onclick="getData('${rc.contextPath}/backend/goods/goods/list','displayArea')">返回</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="tab-pane fade" id="extend-info-tab">
                <form class="form-horizontal" id="extendForm" name="extendForm" action="" method="post">
                    <input type="hidden" class="form-control" name="goodsId" value="${goods.id}" required/>
                    <div class="form-group">
                        <label class="col-md-3 control-label">商品卖点：</label>
                        <div class="col-md-3">
                            <input type="text" id="salePoint" class="form-control" name="salePoint" value="${goods.salePoint}" placeholder="商品卖点，一句话" rangelength="1, 100">
                        </div>
                    </div>
                    <div class="form-group clearfix">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>积分抵扣：</label>
                        <div class="col-md-9">
                            <div class="goods-spec-type">
                                <label class="point-type"><input type="radio" <#if (goods.canUsePoint=='Y')>checked</#if> value="Y" name="canUsePoint">开启</label>
                                <label class="point-type"><input type="radio" <#if (goods.canUsePoint=='N')>checked</#if> value="N" name="canUsePoint">关闭</label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group clearfix">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>会员折扣：</label>
                        <div class="col-md-9">
                            <div class="goods-spec-type">
                                <label class="discount-type"><input type="radio" value="Y" <#if (goods.isMemberDiscount=='Y')>checked</#if> name="isMemberDiscount">有折扣</label>
                                <label class="discount-type"><input type="radio" value="N" <#if (goods.isMemberDiscount=='N')>checked</#if> name="isMemberDiscount">无折扣</label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">初始销量：</label>
                        <div class="col-md-3">
                            <input type="text" id="initSale" class="form-control" name="initSale" value="${goods.initSale}" placeholder="初始销量，正整数" rangelength="1, 10">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">* </span>规格类型：</label>
                        <div class="col-md-9">
                            <div class="goods-spec-type">
                                <label class="spec-type"><input type="radio" <#if (goods.isSingleSpec=='Y')>checked</#if> value="Y" name="isSingleSpec">单规格</label>
                                <label class="spec-type"><input type="radio" <#if (goods.isSingleSpec=='N')>checked</#if> value="N" name="isSingleSpec">多规格</label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">*</span>商品价格：</label>
                        <div class="col-md-3">
                            <input type="text" id="price" class="form-control" name="price" value="${goods.price}" placeholder="商品价格" rangelength="1,100">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"><span class="requiredstar">*</span>划线价格：</label>
                        <div class="col-md-3">
                            <input type="text" id="linePrice" class="form-control" name="linePrice" value="${goods.linePrice}" placeholder="划线价格，长度1-100" rangelength="1, 100">
                        </div>
                    </div>
                    <!--单规格 start-->
                    <div class="single-spec" <#if (goods.isSingleSpec=='N')>style="display:none;"</#if>>
                        <div class="form-group">
                            <label class="col-md-3 control-label"><span class="requiredstar">*</span>库存数量：</label>
                            <div class="col-md-3">
                                <input type="text" id="stock" class="form-control" name="stock" value="${goods.stock}" placeholder="正整数" rangelength="1, 10">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-md-3 control-label">商品重量：</label>
                            <div class="col-md-3">
                                <input type="text" id="weight" class="form-control" name="weight" value="${goods.weight}" placeholder="数字，单位kg" rangelength="1, 10">
                            </div>
                        </div>
                    </div>
                    <!--单规格 end-->
                    <!--多规格 start-->
                    <div class="multi-spec" <#if (goods.isSingleSpec=='Y')>style="display:none;"</#if>>
                        <div class="form-group">
                            <div class="col-md-9">
                                <div class="layui-container">
                                    <form action="" id="skuForm" class="layui-form fairy-form">
                                        <!-- sku参数表 -->
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">规格：</label>
                                            <div class="layui-input-block">
                                                <div id="fairy-spec-table"></div>
                                            </div>
                                        </div>
                                        <!-- 动态sku表 -->
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">sku表：</label>
                                            <div class="layui-input-block">
                                                <div id="fairy-sku-table"></div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--多规格 end-->
                    <div class="form-group clearfix">
                        <label class="col-md-3 control-label"></label>
                        <div class="col-md-9">
                            <button type="button" id="submitExtend" lay-submit lay-filter="submit" class="btn btn-sm btn-success">提交</button>
                            <button type="button" class="btn btn-sm btn-danger" onclick="getData('${rc.contextPath}/backend/goods/goods/list','displayArea')">返回</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="tab-pane fade" id="detail-info-tab">
                <form class="form-horizontal" id="detailForm" name="detailForm" action="" method="post">
                    <input type="hidden" class="form-control" name="goodsId" value="${goods.id}"/>
                    <div class="form-group">
                        <label class="col-md-3 control-label"></label>
                        <div class="col-md-9 goods-description">
                            <script id="description" charset="UTF-8" type="text/plain">${goods.description}</script>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label"></label>
                        <div class="col-md-9">
                            <button type="button" id="submitDetail" class="btn btn-sm btn-success">提交</button>
                            <button type="button" class="btn btn-sm btn-danger" onclick="getData('${rc.contextPath}/backend/goods/goods/list','displayArea')">返回</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script src="<@sp.static/>/assets/plugins/ueditor/ueditor.config.js?v=1.7.9" type="text/javascript" charset="UTF-8"></script>
<script src="<@sp.static/>/assets/plugins/ueditor/ueditor.all.js?v=1.7.9" type="text/javascript" charset="UTF-8"></script>
<script src="<@sp.static/>/assets/plugins/ueditor/lang/zh-cn/zh-cn.js?v=1.7.9" type="text/javascript" charset="UTF-8"></script>
<script src="<@sp.static/>/assets/plugins/skuTable/layui/layui.js?v=1.7.9" charset="UTF-8"></script>
<script src="<@sp.static/>/assets/plugins/skuTable/skuTable.js?v=1.7.9" charset="UTF-8"></script>
<link rel="stylesheet" type="text/css" href="<@sp.static/>/assets/plugins/skuTable/layui/css/layui.css?v=1.7.9" charset="UTF-8"/>
<script>
    layui.config({
        base: './'
    }).use(['form', 'skuTable'], function () {
        var form = layui.form;
        var skuTable = layui.skuTable;

        //示例中的json文件仅做格式返回参考，若多次执行添加规格后再为新增后的规格添加规格值，会发现所有新增的规格都增加了该规格值。注意！此处并非是bug，原因是因为示例中返回的新增规格值id是重复的，而在正常接口请求每次返回的新增规则id是不一样的
        var obj = skuTable.render({
            //规格表容器id
            specTableElemId: 'fairy-spec-table',
            //sku表容器id
            skuTableElemId: 'fairy-sku-table',
            //sku表相同属性值是否合并行
            rowspan: true,
            //上传接口地址
            //接口要求返回格式为 {"code": 200, "data": {"url": "xxx"}, "msg": ""}
            uploadUrl: '${rc.contextPath}/backend/file/upload?sourcePic=picture',
            //添加规格接口地址，如果为空则表示不允许增加规格
            //接口要求返回格式为 {"code": 200, "data": {"id": "xxx"}, "msg": ""}
            specCreateUrl: "${rc.contextPath}/backend/goods/goods/saveSpecName",
            //添加规格值接口地址，如果为空则表示不允许增加规格值
            //接口要求返回格式为 {"code": 200, "data": {"id": "xxx"}, "msg": ""}
            specValueCreateUrl: "${rc.contextPath}/backend/goods/goods/saveSpecValue",
            specDeleteUrl: "${rc.contextPath}/backend/goods/goods/deleteSpec",
            specValueDeleteUrl: "${rc.contextPath}/backend/goods/goods/deleteSpecValue",
            //sku表格配置参数
            skuTableConfig: {
                thead: [
                    {name: '图片', icon: ''},
                    {name: '销售价(元)', icon: ''},
                    {name: '划线价(元)', icon: ''},
                    {name: '重量(kg)', icon: ''},
                    {name: '库存', icon: ''},
                    {name: 'sku编码', icon: ''},
                ],
                tbody: [
                    {type: 'image', field: 'logo', value: '', verify: '', reqtext: ''},
                    {type: 'input', field: 'price', value: '0', verify: 'required|number', reqtext: '销售价不能为空'},
                    {type: 'input', field: 'linePrice', value: '0', verify: 'required|number', reqtext: '市场价不能为空'},
                    {type: 'input', field: 'weight', value: '0', verify: '', reqtext: ''},
                    {type: 'input', field: 'stock', value: '0', verify: 'required|number', reqtext: '库存不能为空'},
                    {type: 'input', field: 'skuNo', value: '', verify: 'required', reqtext: ''},
                ]
            },
            // 规格数据
            specData: ${specData},
            // sku数据
            skuData: ${skuData}
        });
    });
</script>

<script type="application/javascript" charset="UTF-8">
    $(function () {
        UE.getEditor('description', {
            toolbars: [
                ['fullscreen', 'source', 'undo', 'redo', 'bold', 'italic',
                    'underline','fontborder', 'backcolor', 'fontsize', 'fontfamily',
                    'justifyleft', 'justifyright','justifycenter', 'justifyjustify',
                    'strikethrough','superscript', 'subscript', 'removeformat',
                    'formatmatch','autotypeset', 'blockquote', 'pasteplain', '|',
                    'forecolor', 'backcolor','insertorderedlist', 'insertunorderedlist',
                    'selectall', 'cleardoc', 'link', 'unlink','emotion','simpleupload','insertvideo', 'help']
            ],
            iframeCssUrl: "<@sp.static/>/assets/plugins/ueditor/themes/iframe.css?v=1.7.9",
            autoHeightEnabled: true,
            autoFloatEnabled: true,
            initialFrameWidth: 380,
            initialFrameHeight: 600
        });

        // 基本信息提交
        $('#submitBase').click(function () {
            const name = $("#name").val();
            if (name.length < 1) {
                layer.alert('请先填写商品名称！');
                return false;
            }
            const goodsNo = $("#goodsNo").val();
            if (goodsNo.length < 1) {
                layer.alert('请先填写商品编码！');
                return false;
            }
            const logo = $("#filePath1").val();
            if (logo.length < 1) {
                layer.alert('至少上传一张商品图片！');
                return false;
            }
            const sort = $("#sort").val();
            if (sort.length < 0) {
                $("#sort").val("0")
            }

            if ($("#name").val() != null || $("#name").val() != "") {
                $.ajax({
                    type: "POST",
                    data: $('#baseForm').serialize(),
                    url: "${rc.contextPath}/backend/goods/goods/save",
                    success: function (data) {
                        if (data.result) {
                            $(":input[name='goodsId']").val(data.data.goods.id);
                            $("#goodsId").val(data.data.goods.id);
                            layer.alert("恭喜，商品基础信息提交成功！");
                            return;
                        } else {
                            layer.alert(data.msg);
                            return;
                        }
                    }
                })
            }
        });

        $('#submitExtend').click(function () {
            const goodsId = $("#goodsId").val();
            if (goodsId.length < 1) {
                layer.alert('请先提交商品基础信息！');
                return false;
            }

            const price = $("#price").val();
            if (price.length < 1) {
                layer.alert('请先填写商品价格！');
                return false;
            }
            const linePrice = $("#linePrice").val();
            if (linePrice.length < 1) {
                layer.alert('请先填写商品划线价格！');
                return false;
            }

            $.ajax({
                type: "POST",
                data: $('#extendForm').serialize(),
                url: "${rc.contextPath}/backend/goods/goods/save",
                success: function (data) {
                    if (data.result) {
                        $(":input[name='goodsId']").val(data.data.goods.id);
                        $("#goodsId").val(data.data.goods.id);
                        layer.alert("恭喜，商品信息提交成功！");
                        return;
                    } else {
                        layer.alert(data.msg);
                        return;
                    }
                }
            })
        });

        $('#submitDetail').click(function () {
            const goodsId = $("#goodsId").val();
            if (goodsId.length < 1) {
                layer.alert('请先提交商品基础信息！');
                return false;
            }
            $.ajax({
                type: "POST",
                data: $('#detailForm').serialize(),
                url: "${rc.contextPath}/backend/goods/goods/save",
                success: function (data) {
                    if (data.result) {
                        $(":input[name='goodsId']").val(data.data.goods.id);
                        $("#goodsId").val(data.data.goods.id);
                        layer.alert("恭喜，商品详情提交成功！");
                        return;
                    } else {
                        layer.alert(data.msg);
                        return;
                    }
                }
            })
        });

        $('.nav-item').click(function() {
            let id = $(this).attr("id");
            $(this).parent().find('a').removeClass("active");
            $(this).find('a', 0).addClass("active");
            $(".tab-pane").removeClass("active show").addClass("fade");
            $("#"+id+"-tab").addClass("active show").removeClass("fade");
        });

        $('.spec-type').change(function() {
            let isSingle = $('input:radio[name=isSingleSpec]:checked').val();
            if (isSingle == 'Y') {
               $('.multi-spec').css('display', 'none');
               $('.single-spec').css('display', 'block');
            } else {
                $('.multi-spec').css('display', 'block');
                $('.single-spec').css('display', 'none');
            }
        });

        // 新增图片
        $('.add-goods-image').click(function() {
            let num = $(this).parent().find(".upload-item").length + 1;
            let item = '<div class="upload-item">\n' +
                       '<img name="image'+num+'" class="image" id="image'+num+'" src="<@mh.static/>/defaultImage/none.png">\n' +
                       '<input type="file" name="picture'+num+'" id="picture'+num+'" style="display: inline-block" onchange="ajaxFileUpload('+num+', \'${rc.contextPath}/backend\');">\n' +
                       '<a class="label label-danger small-btn delete" href="javascript:void(0)" title="删除该图片"><i class="fa fa-remove"></i>删除</a>' +
                       '<div class="tip">（格式：jpeg/jpg/png）</div>\n' +
                       '<input type="hidden" placeholder="存储路径" name="image" id="filePath'+num+'" value="" onchange="changeImagePath(\'<@mh.static/>\', '+num+')">\n' +
                       '</div>';
            $(this).parent().find(".upload-list", 0).append(item);
        });

        // 删除商品的图片
        $(document).on('click', '.delete', function () {
            $(this).parent().remove();
        })

        $('#extendForm').validate({
            rules: {},
            messages: {},
            errorPlacement: function (error, element) {
                error.appendTo(element.parent());
            },
            submitHandler: function () {
                postDataByFormParams('${rc.contextPath}/backend/goods/goods/save', 'displayArea', 'extendForm');
            }
        })

        $('#detailForm').validate({
            rules: {},
            messages: {},
            errorPlacement: function (error, element) {
                error.appendTo(element.parent());
            },
            submitHandler: function () {
                postDataByFormParams('${rc.contextPath}/backend/goods/goods/save', 'displayArea', 'detailForm');
            }
        })
    })
</script>

